package com.sjb.cp.manager.websocket;

import cn.hutool.core.util.StrUtil;
import com.sjb.cp.manager.auth.SpaceUserAuthManager;
import com.sjb.cp.model.constant.SpaceUserPermissionConstant;
import com.sjb.cp.model.enums.SpaceLevelEnum;
import com.sjb.cp.model.enums.SpaceTypeEnum;
import com.sjb.cp.model.po.Picture;
import com.sjb.cp.model.po.Space;
import com.sjb.cp.model.po.User;
import com.sjb.cp.service.PictureService;
import com.sjb.cp.service.SpaceService;
import com.sjb.cp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author:sjb
 * @CreateTime:2025-02-20
 * @Description: webSocket拦截器
 * @Version：1.0
 */
@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest serverHttpRequest, @NotNull ServerHttpResponse serverHttpResponse,
                                   @NotNull WebSocketHandler webSocketHandler, @NotNull Map<String, Object> map) throws Exception {

        if (serverHttpRequest instanceof HttpServletRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
            String pictureId = servletRequest.getParameter("pictureId");
            if (StrUtil.isEmpty(pictureId)) {
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            User loginUser = userService.getLoginUser(servletRequest);
            if (loginUser == null) {
                log.error("用户未登录，拒绝握手");
                return false;
            }
            Picture picture = pictureService.getById(pictureId);
            if (picture == null) {
                log.error("请求图片不存在，拒绝握手");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space = null;
            if (spaceId != null) {
                space = spaceService.getById(spaceId);
                if (space == null) {
                    log.error("空间不存在，拒绝握手");
                    return false;
                }
                if (space.getSpaceType() != SpaceTypeEnum.TEAM.getValue()){
                    log.info("不是团队空间，拒绝握手");
                    return false;
                }
            }
            List<String> permissionsList = spaceUserAuthManager.getPermissionsList(space, loginUser);
            if (!permissionsList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)){
                log.error("没有编辑权限，拒绝握手");
                return false;
            }
            map.put("pictureId", pictureId);
            map.put("user", loginUser);
            map.put("userId", loginUser.getId());
        }
        return true;
    }

    @Override
    public void afterHandshake(@NotNull ServerHttpRequest serverHttpRequest, @NotNull ServerHttpResponse serverHttpResponse,
                               @NotNull WebSocketHandler webSocketHandler, Exception e) {

    }
}
